<?php
namespace app\subscribe;

use think\Event;
use think\facade\Log;

use app\model\TorrentBank;
use app\helper\CommonHelper;

/**
 * 通过事件订阅的方式将种子库逻辑从主逻辑中拆分
 */
class TorrentSubscribe
{
    // 绑定订阅事件函数
    public function subscribe(Event $event)
    {
        $event->listen('torrent_add', [$this,'add']);
        $event->listen('torrent_remove',[$this,'remove']);
    }

    /**
     * 通过pieces_hash从站点获取到新数据时触发
     * @param array $event
     * 例:
     * [
     *   'site_url'   => '{site_url}',
     *   'torrents'   => [
     *     '{pieces_hash}'  => '{torrent_id}',
     *   ],
     * ]
     * @return void
     */
    public function add(array $event)
    {
        $site_url = $event['site_url'];
        $torrents = $event['torrents'];

        if(!$site_url || !is_array($torrents) || count($torrents) == 0){
            return;
        }

        $site_url = CommonHelper::site_url_standard($site_url, true);
        $pieces_hash_list = array_keys($torrents);

        $has_torrent_list = TorrentBank::query()
            ->where(['site_url' => $site_url])
            ->whereIn('pieces_hash', $pieces_hash_list)
            ->select()
            ->toArray();

        // 生成插入的实体，约束一下字段
        $torrents_add = [];
        foreach ($torrents as $key => $value){
            $torrents_add[] = [
                'site_url'    =>  $site_url,
                'pieces_hash' =>  $key,
                'torrent_id'  =>  $value,
            ];
        }

        // 把已存在的先删了，再插入新的，暂时不加事务
        if(count($has_torrent_list) > 0 ){
            TorrentBank::query()
                ->where([
                    'id' => array_column($has_torrent_list, 'id')
                ])
                ->delete();
        }
        TorrentBank::mk()->insertAll($torrents_add);
    }

    /**
     * qb、tr添加种子返回失败触发
     * @param array $event
     * 例:
     * [
     *   'site_url'      => '{site_url}',
     *   'pieces_hash'   => '{pieces_hash}',
     * ]
     * @return void
     */
    public function remove(array $event)
    {
        $site_url = $event['site_url'];
        $pieces_hash = $event['pieces_hash'];

        if(!$site_url || !$pieces_hash){
            return;
        }

        $where = [
            'site_url'    => CommonHelper::site_url_standard($site_url, true),
            'pieces_hash' => $pieces_hash,
        ];
        TorrentBank::query()->where($where)->delete();

        $where['site_url'] = $site_url;
        Log::notice('torrent_remove finished.' . json_encode($where));
    }
}
